//
//  CircleViewController.m
//  PlayCatchGame
//
//  Created by 流言 on 2018/1/15.
//  Copyright © 2018年 清正. All rights reserved.
//
#import "RealPublishCircleVC.h"
#import "CircleViewController.h"
#import "CircleViewCell.h"
#import "AppHeader.h"
#import "XLPhotoBrowser.h"

#import "PublishCircleVC.h"
#import "CircleModel.h"
#import "circle.h"

@interface CircleViewController () <UITableViewDataSource, UITableViewDelegate, XLPhotoBrowserDelegate> {
    NSInteger itemCount;
    CGFloat itemSpace;
}

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (strong, nonatomic) NSMutableArray<CircleModel *> *dataArray;
/** 上一次的请求参数 */
@property (nonatomic, strong) NSDictionary *params;
/** 当前页码 */
@property (nonatomic, assign) NSInteger pageNowO;
@end

@implementation CircleViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self setupRefresh];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    itemCount =3;
    itemSpace =0;
    self.tableView.rowHeight =UITableViewAutomaticDimension;
    [self showNavigatioBarSeat:BaseBarItemDirectionRight withImage:[UIImage imageNamed:@"fabu"]];
//    self.dataArray =[NSMutableArray arrayWithObjects:@"1", @"2", @"3", @"4", @"5", @"6", nil];
}

-(void)setupRefresh
{
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNew)];
    self.tableView.mj_header.autoChangeAlpha = YES;
    [self.tableView.mj_header beginRefreshing];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
    
}
/**
 * 加载新的数据
 */
-(void)loadNew
{
       self.pageNowO = 1 ;
    // 结束上拉
    [self.tableView.mj_footer endRefreshing];
   
    NSMutableDictionary *parmsO = [NSMutableDictionary dictionary];
    parmsO[@"current"] = @"1";
    
    self.params = parmsO;
    
    [HttpUrl GET:@"dynamics/selectDynamicsByPage"dict:parmsO hud:self.view isShow:YES WithSuccessBlock:^(id data) {
        if (BB_isSuccess) {
            [self.dataArray removeAllObjects];
            for (NSDictionary *dic in data[@"data"][@"list"]) {
                CircleModel *model = [CircleModel initialModelWithKeyValues:dic];
                [self.dataArray addObject:model];
            }
        }
        else{
            [TheGlobalMethod xianShiAlertView:data[@"msg"] controller:self];
        }
        [self.tableView reloadData];
    }];
    self.pageNowO = 1 ;
    [self.tableView.mj_header endRefreshing];
    
}

-(void)loadMore
{
     NSInteger page = self.pageNowO + 1;
    // 结束下拉
    [self.tableView.mj_header endRefreshing];
    
    // 参数
    NSMutableDictionary *parmsO = [NSMutableDictionary dictionary];
    parmsO[@"current"] = @(page);
    self.params = parmsO;
    
    [HttpUrl GET:@"dynamics/selectDynamicsByPage"dict:parmsO hud:self.view isShow:YES WithSuccessBlock:^(id data) {
        if (BB_isSuccess) {
            if (self.params != parmsO) return;
            for (NSDictionary *dic in data[@"data"][@"list"]) {
                
                CircleModel *model = [CircleModel initialModelWithKeyValues:dic];
                [self.dataArray addObject:model];
            }
            
//            [self.dataArray addObjectsFromArray:newInventory];
        }
        else{
            [TheGlobalMethod xianShiAlertView:data[@"msg"] controller:self];
        }
        [self.tableView reloadData];
    }];
    self.pageNowO = page;
    [self.tableView reloadData];
    [self.tableView.mj_footer endRefreshing];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(tableView.frame), 0.1)];
    headerView.backgroundColor =tableView.backgroundColor;
    
    return headerView;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CircleViewCell *cell =[tableView dequeueReusableCellWithIdentifier:@"CircleViewCell"];
    if (!cell) {
        cell =[CircleViewCell findCellWithIdentifier:@"CircleViewCell"];
        cell.selectionStyle =UITableViewCellSelectionStyleNone;
    }
    
    CircleModel *model = self.dataArray[indexPath.row];
    
    cell.contentLabel.text = model.content;
    cell.nameLabel.text = [NSString  stringWithFormat:@"%@", model.user.userName];
    cell.subLabel.text = [NSString stringWithFormat:@"抓中次数：%ld次",model.user.userAccount.winTimes];
    cell.contentLabel.text = [NSString stringWithFormat:@"%@", model.content];
    
//    NSMutableArray *imageArray =@[[UIImage imageNamed:@"defaut"], [UIImage imageNamed:@"defaut"], [UIImage imageNamed:@"defaut"], [UIImage imageNamed:@"defaut"], [UIImage imageNamed:@"defaut"], [UIImage imageNamed:@"defaut"], [UIImage imageNamed:@"defaut"], [UIImage imageNamed:@"defaut"], [UIImage imageNamed:@"defaut"]].mutableCopy;
    NSMutableArray *imageArray = model.picUrls;
    
    CGFloat imageHeight = ceilf((imageArray.count)/(itemCount*1.0)) *(KScreenWidth-43-itemSpace*(itemCount-1))/((itemCount*1.0));
    cell.imageBg_height.constant =imageHeight+10;

    ImageItemView *imageCell =[cell.imageBgView viewWithTag:200];
    if (!imageCell) {
        imageCell =[ImageItemView loadNib:@"ImageItemView" frame:CGRectMake(0, 0, KScreenWidth-43, cell.imageBg_height.constant)];
        imageCell.tag =200;
        imageCell.itemSpace =itemSpace;
        imageCell.itemCount =itemCount;
        imageCell.isDelete =NO;
        imageCell.sectionEdgeInsets =UIEdgeInsetsMake(0, 0, 5, 0);
        [cell.imageBgView addSubview:imageCell];
        [imageCell didCollectionItemBlock:^(NSInteger indexRow, BOOL isAdd) {
            if (!isAdd) {
                XLPhotoBrowser *browser = [XLPhotoBrowser showPhotoBrowserWithImages:imageArray currentImageIndex:indexRow];
                browser.browserStyle = XLPhotoBrowserStylePageControl;
                [browser setActionSheetWithTitle:@"操作" delegate:self cancelButtonTitle:@"取消" deleteButtonTitle:nil otherButtonTitles:@"保存", nil];
                NSLog(@"预览图片");
            }
        }];
    }
    // 必须放外围(防止重用)
    imageCell.maxCount =imageArray.count;
    imageCell.imageArray =imageArray;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}

- (void)barItemRightButtonClick:(UIButton *)button {
    PublishCircleVC *publishVC =[[PublishCircleVC alloc]initWithNibName:@"PublishCircleVC" bundle:nil];
//    RealPublishCircleVC *publishVC = [[RealPublishCircleVC alloc] initWithNibName:@"RealPublishCircleVC" bundle:nil];
    publishVC.title=@"圈子发布";
    publishVC.hidesBottomBarWhenPushed =YES;
    [self.navigationController pushViewController:publishVC animated:YES];
}


#pragma mark - 长按下载图片
- (void)photoBrowser:(XLPhotoBrowser *)browser clickActionSheetIndex:(NSInteger)actionSheetindex currentImageIndex:(NSInteger)currentImageIndex {
    if (actionSheetindex ==0) {
        [browser saveCurrentShowImage];
    }
}

#pragma mark - Property Override
- (NSMutableArray<CircleModel *> *)dataArray {
    if (_dataArray == nil) {
        _dataArray = @[].mutableCopy;
    }
    return _dataArray;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
